home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / share / pyshared / ufw / util.py < prev   
Encoding:
Python Source  |  2008-10-08  |  12.2 KB  |  498 lines

  1. #
  2. # util.py: utility functions for ufw
  3. #
  4. # Copyright (C) 2008 Canonical Ltd.
  5. #
  6. #    This program is free software: you can redistribute it and/or modify
  7. #    it under the terms of the GNU General Public License version 3,
  8. #    as published by the Free Software Foundation.
  9. #
  10. #    This program is distributed in the hope that it will be useful,
  11. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #    GNU General Public License for more details.
  14. #
  15. #    You should have received a copy of the GNU General Public License
  16. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  17. #
  18.  
  19. import os
  20. import re
  21. import shutil
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. from tempfile import mkstemp
  27.  
  28. debugging = False
  29.  
  30.  
  31. def get_services_proto(port):
  32.     '''Get the protocol for a specified port from /etc/services'''
  33.     proto = ""
  34.     try:
  35.         socket.getservbyname(port)
  36.     except Exception:
  37.         raise
  38.  
  39.     try:
  40.         socket.getservbyname(port, "tcp")
  41.         proto = "tcp"
  42.     except Exception:
  43.         pass
  44.  
  45.     try:
  46.         socket.getservbyname(port, "udp")
  47.         if proto == "tcp":
  48.             proto = "any"
  49.         else:
  50.             proto = "udp"
  51.     except Exception:
  52.         pass
  53.  
  54.     return proto
  55.  
  56.  
  57. def parse_port_proto(str):
  58.     '''Parse port or port and protocol'''
  59.     port = ""
  60.     proto = ""
  61.     tmp = str.split('/')
  62.     if len(tmp) == 1:
  63.         port = tmp[0]
  64.         proto = "any"
  65.     elif len(tmp) == 2:
  66.         port = tmp[0]
  67.         proto = tmp[1]
  68.     else:
  69.         raise ValueError
  70.     return (port, proto)
  71.  
  72.  
  73. def valid_address6(addr):
  74.     '''Verifies if valid IPv6 address'''
  75.     if not socket.has_ipv6:
  76.         warn("python does not have IPv6 support.")
  77.         return False
  78.  
  79.     # quick and dirty test
  80.     if len(addr) > 43 or not re.match(r'^[a-fA-F0-9:\./]+$', addr):
  81.         return False
  82.  
  83.     net = addr.split('/')
  84.     try:
  85.         socket.inet_pton(socket.AF_INET6, net[0])
  86.     except Exception:
  87.         return False
  88.  
  89.     if len(net) > 2:
  90.         return False
  91.     elif len(net) == 2:
  92.         # Check netmask specified via '/'
  93.         if not _valid_cidr_netmask(net[1], True):
  94.             return False
  95.  
  96.     return True
  97.  
  98.  
  99. def valid_address4(addr):
  100.     '''Verifies if valid IPv4 address'''
  101.     # quick and dirty test
  102.     if len(addr) > 31 or not re.match(r'^[0-9\./]+$', addr):
  103.         return False
  104.  
  105.     net = addr.split('/')
  106.     try:
  107.         socket.inet_pton(socket.AF_INET, net[0])
  108.         if not _valid_dotted_quads(net[0], False):
  109.             return False
  110.     except Exception:
  111.         return False
  112.  
  113.     if len(net) > 2:
  114.         return False
  115.     elif len(net) == 2:
  116.         # Check netmask specified via '/'
  117.         if not valid_netmask(net[1], False):
  118.             return False
  119.  
  120.     return True
  121.  
  122.  
  123. def valid_netmask(nm, v6):
  124.     '''Verifies if valid cidr or dotted netmask'''
  125.     return _valid_cidr_netmask(nm, v6) or _valid_dotted_quads(nm, v6)
  126.  
  127.  
  128. #
  129. # valid_address()
  130. #    version="6" tests if a valid IPv6 address
  131. #    version="4" tests if a valid IPv4 address
  132. #    version="any" tests if a valid IP address (IPv4 or IPv6)
  133. #
  134. def valid_address(addr, version="any"):
  135.     '''Validate IP addresses'''
  136.     if version == "6":
  137.         return valid_address6(addr)
  138.     elif version == "4":
  139.         return valid_address4(addr)
  140.     elif version == "any":
  141.         return valid_address4(addr) or valid_address6(addr)
  142.  
  143.     raise ValueError
  144.  
  145.  
  146. def normalize_address(orig, v6):
  147.     '''Convert address to standard form. Use no netmask for IP addresses. If
  148.        If netmask is specified and not all 1's, for IPv4 use cidr if possible, 
  149.        otherwise dotted netmask and for IPv6, use cidr.
  150.     '''
  151.     net = []
  152.     changed = False
  153.     version = "4"
  154.     if v6:
  155.         version = "6"
  156.  
  157.     if '/' in orig:
  158.         net = orig.split('/')
  159.         # Remove host netmasks
  160.         if v6 and net[1] == "128":
  161.             del net[1]
  162.         elif not v6:
  163.             if net[1] == "32" or net[1] == "255.255.255.255":
  164.                 del net[1]
  165.     else:
  166.         net.append(orig)
  167.  
  168.     if not v6 and len(net) == 2 and _valid_dotted_quads(net[1], v6):
  169.         try:
  170.             net[1] = _dotted_netmask_to_cidr(net[1], v6)
  171.         except Exception:
  172.             # Not valid cidr, so just use the dotted quads
  173.             pass
  174.  
  175.     addr = net[0]
  176.     if len(net) == 2:
  177.         addr += "/" + net[1]
  178.         if not v6:
  179.             network = _address4_to_network(addr)
  180.             if network != addr:
  181.                 dbg_msg = "Using '%s' for address '%s'" % (network, addr)
  182.                 debug(dbg_msg)
  183.                 addr = network
  184.                 changed = True
  185.  
  186.     if not valid_address(addr, version):
  187.         dbg_msg = "Invalid address '%s'" % (addr)
  188.         debug(dbg_msg)
  189.         raise ValueError
  190.  
  191.     return (addr, changed)
  192.  
  193.  
  194. def open_file_read(f):
  195.     '''Opens the specified file read-only'''
  196.     try:
  197.         orig = open(f, 'r')
  198.     except Exception:
  199.         raise
  200.  
  201.     return orig
  202.  
  203.  
  204. def open_files(f):
  205.     '''Opens the specified file read-only and a tempfile read-write.'''
  206.     try:
  207.         orig = open_file_read(f)
  208.     except Exception:
  209.         raise
  210.  
  211.     try:
  212.         (tmp, tmpname) = mkstemp()
  213.     except Exception:
  214.         orig.close()
  215.         raise
  216.  
  217.     return { "orig": orig, "origname": f, "tmp": tmp, "tmpname": tmpname }
  218.  
  219.  
  220. def close_files(fns, update = True):
  221.     '''Closes the specified files (as returned by open_files), and update
  222.        original file with the temporary file.
  223.     '''
  224.     fns['orig'].close()
  225.     os.close(fns['tmp'])
  226.  
  227.     if update:
  228.         try:
  229.             shutil.copystat(fns['origname'], fns['tmpname'])
  230.             shutil.copy(fns['tmpname'], fns['origname'])
  231.         except Exception:
  232.             raise
  233.  
  234.     try:
  235.         os.unlink(fns['tmpname'])
  236.     except OSError, e:
  237.         raise
  238.  
  239.  
  240. def cmd(command):
  241.     '''Try to execute the given command.'''
  242.     debug(command)
  243.     try:
  244.         sp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  245.     except OSError, e:
  246.         return [127, str(e)]
  247.  
  248.     out = sp.communicate()[0]
  249.     return [sp.returncode,out]
  250.  
  251.  
  252. def cmd_pipe(command1, command2):
  253.     '''Try to pipe command1 into command2.'''
  254.     try:
  255.         sp1 = subprocess.Popen(command1, stdout=subprocess.PIPE)
  256.         sp2 = subprocess.Popen(command2, stdin=sp1.stdout)
  257.     except OSError, e:
  258.         return [127, str(e)]
  259.  
  260.     out = sp2.communicate()[0]
  261.     return [sp2.returncode,out]
  262.  
  263.  
  264. def error(msg, exit=True):
  265.     '''Print error message and exit'''
  266.     print >> sys.stderr, "ERROR: %s" % (msg)
  267.     if exit:
  268.         sys.exit(1)
  269.  
  270.  
  271. def warn(msg):
  272.     '''Print warning message'''
  273.     print >> sys.stderr, "WARN: %s" % (msg)
  274.  
  275.  
  276. def debug(msg):
  277.     '''Print debug message'''
  278.     if debugging:
  279.         print >> sys.stderr, "DEBUG: %s" % (msg)
  280.  
  281.  
  282. def word_wrap(text, width):
  283.     '''
  284.     A word-wrap function that preserves existing line breaks
  285.     and most spaces in the text. Expects that existing line
  286.     breaks are posix newlines (\n).
  287.     '''
  288.     return reduce(lambda line, word, width=width: '%s%s%s' %
  289.                   (line,
  290.                    ' \n'[(len(line)-line.rfind('\n')-1
  291.                          + len(word.split('\n',1)[0]
  292.                               ) >= width)],
  293.                    word),
  294.                   text.split(' ')
  295.                  )
  296.  
  297.  
  298. def wrap_text(text):
  299.     '''Word wrap to a specific width'''
  300.     return word_wrap(text, 75)
  301.  
  302.  
  303. def human_sort(list):
  304.     '''Sorts list of strings into numeric order, with text case-insensitive.
  305.        Modifies list in place.
  306.  
  307.        Eg:
  308.        [ '80', 'a222', 'a32', 'a2', 'b1', '443', 'telnet', '3', 'http', 'ZZZ']
  309.  
  310.        sorts to:
  311.        ['3', '80', '443', 'a2', 'a32', 'a222', 'b1', 'http', 'telnet', 'ZZZ']
  312.     '''
  313.     norm = lambda t: int(t) if t.isdigit() else t.lower()
  314.     list.sort(key=lambda k: [ norm(c) for c in re.split('([0-9]+)', k)])
  315.  
  316.  
  317. def get_ppid(p=os.getpid()):
  318.     '''Finds parent process id for pid based on /proc/<pid>/stat. See
  319.        'man 5 proc' for details.
  320.     '''
  321.     try:
  322.         pid = int(p)
  323.     except:
  324.         raise ValueError("pid must be an integer")
  325.  
  326.     name = os.path.join("/proc", str(pid), "stat")
  327.     if not os.path.isfile(name):
  328.         raise IOError("Couldn't find '%s'" % (name))
  329.  
  330.     try:
  331.         ppid = file(name).readlines()[0].split()[3]
  332.     except Exception:
  333.         raise
  334.  
  335.     return int(ppid)
  336.  
  337.  
  338. def under_ssh(pid=os.getpid()):
  339.     '''Determine if current process is running under ssh'''
  340.     try:
  341.         ppid = get_ppid(pid)
  342.     except IOError, e:
  343.         warn_msg = _("Couldn't find pid (is /proc mounted?)")
  344.         warn(warn_msg)
  345.         return False
  346.     except Exception:
  347.         err_msg = _("Couldn't find parent pid for '%s'") % (str(pid))
  348.         raise ValueError(err_msg)
  349.  
  350.     # pid '1' is 'init' and '0' is the kernel. This should still work when
  351.     # pid randomization is in use, but needs to be checked.
  352.     if pid == 1 or ppid <= 1:
  353.         return False
  354.  
  355.     path = os.path.join("/proc", str(ppid), "stat")
  356.     if not os.path.isfile(path):
  357.         err_msg = _("Couldn't find '%s'") % (path)
  358.         raise ValueError(err_msg)
  359.  
  360.     try:
  361.         exe = file(path).readlines()[0].split()[1]
  362.     except:
  363.         err_msg = _("Could not find executable for '%s'") % (path)
  364.         raise ValueError(err_msg)
  365.     debug("under_ssh: exe is '%s'" % (exe))
  366.  
  367.     if exe == "(sshd)":
  368.         return True
  369.     else:
  370.         return under_ssh(ppid)
  371.  
  372.  
  373. #
  374. # Internal helper functions
  375. #
  376. def _valid_cidr_netmask(nm, v6):
  377.     '''Verifies cidr netmasks'''
  378.     num = 32
  379.     if v6:
  380.         num = 128
  381.  
  382.     if not re.match(r'^[0-9]+$', nm) or int(nm) < 0 or int(nm) > num:
  383.         return False
  384.  
  385.     return True
  386.  
  387.  
  388. def _valid_dotted_quads(nm, v6):
  389.     '''Verifies dotted quad ip addresses and netmasks'''
  390.     if v6:
  391.         return False
  392.     else:
  393.         if re.match(r'^[0-9]+\.[0-9\.]+$', nm):
  394.             quads = re.split('\.', nm)
  395.             if len(quads) != 4:
  396.                 return False
  397.             for q in quads:
  398.                 if not q or int(q) < 0 or int(q) > 255:
  399.                     return False
  400.         else:
  401.             return False
  402.  
  403.     return True
  404.  
  405. #
  406. # _dotted_netmask_to_cidr()
  407. # Returns:
  408. #   cidr integer (0-32 for ipv4 and 0-128 for ipv6)
  409. #
  410. # Raises exception if cidr cannot be found
  411. #
  412. def _dotted_netmask_to_cidr(nm, v6):
  413.     '''Convert netmask to cidr. IPv6 dotted netmasks are not supported.'''
  414.     cidr = ""
  415.     if v6:
  416.         raise ValueError
  417.     else:
  418.         if not _valid_dotted_quads(nm, v6):
  419.             raise ValueError
  420.  
  421.         mbits = 0
  422.         bits = long(struct.unpack('>L',socket.inet_aton(nm))[0])
  423.         found_one = False
  424.         for n in range(32):
  425.             if (bits >> n) & 1 == 1:
  426.                 found_one = True
  427.             else:
  428.                 if found_one:
  429.                     mbits = -1
  430.                     break
  431.                 else:
  432.                     mbits += 1
  433.  
  434.         if mbits >= 0 and mbits <= 32:
  435.             cidr = str(32 - mbits)
  436.  
  437.     if not _valid_cidr_netmask(cidr, v6):
  438.         raise ValueError
  439.  
  440.     return cidr
  441.  
  442.  
  443. #
  444. # _cidr_to_dotted_netmask()
  445. # Returns:
  446. #   dotted netmask string
  447. #
  448. # Raises exception if dotted netmask cannot be found
  449. #
  450. def _cidr_to_dotted_netmask(cidr, v6):
  451.     '''Convert cidr to netmask. IPv6 dotted netmasks not supported.'''
  452.     nm = ""
  453.     if v6:
  454.         raise ValueError
  455.     else:
  456.         if not _valid_cidr_netmask(cidr, v6):
  457.             raise ValueError
  458.         bits = 0L
  459.         for n in range(32):
  460.             if n < int(cidr):
  461.                 bits |= 1<<31 - n
  462.         nm = socket.inet_ntoa(struct.pack('>L', bits))
  463.  
  464.     if not _valid_dotted_quads(nm, v6):
  465.         raise ValueError
  466.  
  467.     return nm
  468.  
  469. def _address4_to_network(addr):
  470.     '''Convert an IPv4 address and netmask to a network address'''
  471.     if '/' not in addr:
  472.         debug("_address4_to_network: skipping address without a netmask")
  473.         return addr
  474.  
  475.     tmp = addr.split('/')
  476.     if len(tmp) != 2 or not _valid_dotted_quads(tmp[0], False):
  477.         raise ValueError
  478.  
  479.     host = tmp[0]
  480.     orig_nm = tmp[1]
  481.  
  482.     nm = orig_nm
  483.     if _valid_cidr_netmask(nm, False):
  484.         try:
  485.             nm = _cidr_to_dotted_netmask(nm, False)
  486.         except Exception:
  487.             raise
  488.  
  489.     # Now have dotted quad host and nm, find the network
  490.     host_bits = long(struct.unpack('>L',socket.inet_aton(host))[0])
  491.     nm_bits = long(struct.unpack('>L',socket.inet_aton(nm))[0])
  492.  
  493.     network_bits = host_bits & nm_bits
  494.     network = socket.inet_ntoa(struct.pack('>L', network_bits))
  495.  
  496.     return network + "/" + orig_nm
  497.  
  498.